package angle.controller;

import angle.pojo.Role;
import angle.pojo.User;
import angle.service.role.RoleService;
import angle.service.user.UserService;
import angle.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /*进入登录页面*/
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "redirect:/login.jsp";
    }

    /*登录网站*/
    @RequestMapping("/login")
    public ModelAndView login(User user, HttpSession session) {

        ModelAndView mav = new ModelAndView();
        User user1 = userService.queryUserById(user);

        if (user1 != null) {
            mav.addObject("user", user1);
            session.setAttribute("user", user1);
            mav.setViewName("frame");
        } else {
            mav.addObject("error", "用户名或密码错误");
            mav.setViewName("forward:/login.jsp");
        }
        return mav;
    }

    /*退出登录*/
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/login.jsp";
    }

    /*跳转到密码修改页面*/
    @RequestMapping("/toModifypwd")
    public String toModifypwd() {
        return "pwdmodify";
    }

    /*密码修改*/
    @RequestMapping("/ModifyPwd")
    public ModelAndView ModifyPWD(HttpServletResponse response, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        User user = (User) request.getSession().getAttribute("user");
        String password = request.getParameter("newpassword");
        String method = request.getParameter("method");
        if (method.equals("savepwd") && method != null) {
            if (user != null && !StringUtils.isNullOrEmpty(password)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", user.getId());
                map.put("password", password);
                int flag = userService.updatePwd(map);
                if (flag > 0) {
                    mav.addObject("message", "修改密码成功，请刷新页面");
                    //移除session会使得页面直接退出
                    request.getSession().removeAttribute("user");
                    /*mav.setViewName("redirect:/user/ModifyPwd");*/
                    mav.setViewName("pwdmodify");
                } else {
                    mav.addObject("message", "修改密码失败");
                    mav.setViewName("pwdmodify");
                }
            } else {
                mav.addObject("message", "新密码有问题");
                mav.setViewName("pwdmodify");
            }
        }
        //ajax动态异步验证旧密码
        else if (method.equals("oldpwd") && method != null) {
            String oldPwd = request.getParameter("oldpassword");
            //使用一个map来存放要向js页面传入的参数
            Map<String, String> resultMap = new HashMap<String, String>();
            if (user == null) {
                resultMap.put("result", "sessionerror");
            } else if (StringUtils.isNullOrEmpty(oldPwd)) {
                resultMap.put("result", "error");
            } else {
                if (oldPwd.equals(user.getUserPassword())) {
                    resultMap.put("result", "true");
                } else {
                    resultMap.put("result", "false");
                }
            }
            try {
                //设置接收的是json参数
                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.write(JSONArray.toJSONString(resultMap));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }

    /*实现用户列表页面,动态实现用户删除*/
    @RequestMapping("/userlist")
    public ModelAndView userList(HttpServletRequest req, HttpServletResponse resp) {
        ModelAndView mav = new ModelAndView();
        //从前端获取数据
        String method = req.getParameter("method");
        if (method.equals("query") && method != null) {
            String queryUserName = req.getParameter("queryName");
            String userRole = req.getParameter("queryUserRole");
            String pageIndex = req.getParameter("pageIndex");
            //设置每页到显示个数
            int pageSize = 5;
            //设置当前页面值
            int currentPageNo = 1;
            //设置用户角色初始值，防止为空
            int queryUserRole = 0;
            if (userRole != null && !userRole.equals("")) {
                queryUserRole = Integer.parseInt(userRole);
            }
            //判断防止传入空字符串导致动态sql错误拼接从而查询失败
            if (queryUserName == null || queryUserName == "") {
                queryUserName = null;
            }
            //判断页面到当前页，保证页面数不为空
            if (pageIndex != null) {
                try {
                    currentPageNo = Integer.parseInt(pageIndex);
                } catch (Exception e) {
                    mav.setViewName("redirect:/error.jsp");
                    return mav;
                }
            }
            //查询需要到map
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userName", queryUserName);
            map.put("userRole", queryUserRole);
            map.put("currentPageNo", (currentPageNo - 1) * pageSize);
            map.put("pageSize", pageSize);

            //获取用户总数
            int totalCount = userService.queryUserCount(map);
            //获取用户列表
            List<User> userList = userService.getUserList(map);
            //将每个用户的角色名查出
            for (User user : userList) {
                user.setUserRoleName(roleService.getRoleById(user.getUserRole()).getRoleName());
            }
            //分页实现
            PageSupport pageSupport = new PageSupport();
            pageSupport.setCurrentPageNo(currentPageNo);
            pageSupport.setPageSize(pageSize);
            pageSupport.setTotalCount(totalCount);
            //获取页面总数
            int totalPageCount = pageSupport.getTotalPageCount();
            //控制首尾页跳转
            if (currentPageNo < 1) {
                currentPageNo = 1;
            } else if (currentPageNo > totalPageCount) {
                currentPageNo = totalPageCount;
            }
            //获取角色列表
            List<Role> roleList = roleService.getRoleList();
            //给试图层传递参数
            mav.addObject("roleList", roleList);
            mav.addObject("userList", userList);
            mav.addObject("totalCount", totalCount);
            mav.addObject("currentPageNo", currentPageNo);
            mav.addObject("totalPageCount", totalPageCount);
            //保证再点击查询之后，查询框中到内容还在
            mav.addObject("queryUserName", queryUserName);
            mav.addObject("queryUserRole", userRole);
            mav.setViewName("userlist");
        }
        /*ajax动态删除用户实现*/
        else if (method.equals("deluser") && method != null) {
            String id = req.getParameter("uid");
            Integer delId = 0;
            try {
                delId = Integer.parseInt(id);
            } catch (Exception e) {
                delId = 0;
            }
            Map<String, String> resultMap = new HashMap<String, String>();
            if (delId <= 0) {
                resultMap.put("delResult", "notexist");
            } else {
                if (userService.deleteUserById(delId) > 0) {
                    resultMap.put("delResult", "true");
                } else {
                    resultMap.put("delResult", "false");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                resp.setContentType("application/json;charset=utf-8");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = resp.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
            mav.setViewName("userlist");
        }
        return mav;
    }

    /*跳转到用户添加界面*/
    @RequestMapping("/touseradd")
    public String toUserAdd() {
        return "useradd";
    }

    /*用户添加*/
    @RequestMapping(value = "/useradd", produces = "application/json; charset=utf-8")
    public ModelAndView userAdd(User user, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add") && method != null) {
            String birthday = request.getParameter("birthdays");
            try {
                user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            user.setCreationDate(new Date());
            user.setCreatedBy(((User) request.getSession().getAttribute("user")).getId());
            int flag = 0;
            flag = userService.userAdd(user);
            if (flag > 0) {
                mav.setViewName("redirect:/user/userlist?method=query");
            } else {
                mav.setViewName("useradd");
            }
        }
        //ajax动态获取角色选择栏参数
        else if (method.equals("getrolelist") && method != null) {
            List<Role> roleList = roleService.getRoleList();
            try {
                //将roleList转换成json对象
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONArray.toJSONString(roleList));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证登录账号userCode是否已经存在
        else if (method.equals("ucexist") && method != null) {
            //判断用户账号是否可用
            String userCode = request.getParameter("userCode");
            //用于存放对userCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断userCode是否为空
            if (StringUtils.isNullOrEmpty(userCode)) {
                //userCode == null || userCode.equals("")
                resultMap.put("userCode", "exist");
            } else {
                User user1 = new User();
                user1.setUserCode(userCode);
                user1 = userService.queryUserById(user1);
                if (null != user1) {
                    resultMap.put("userCode", "exist");
                } else {
                    resultMap.put("userCode", "notexist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }

    /*用户查看功能*/
    @RequestMapping("/userview")
    public ModelAndView userView(int id) {
        ModelAndView mav = new ModelAndView();
        User user = new User();
        //更具id查询出当前选中的用户
        user.setId(id);
        user = userService.queryUserById(user);
        //设置角色名
        user.setUserRoleName(roleService.getRoleById(user.getUserRole()).getRoleName());
        //设置日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String birthday = dateFormat.format(user.getBirthday());
        //将数据传入前端
        mav.addObject("birthday", birthday);
        mav.addObject("users", user);
        mav.setViewName("userview");
        return mav;
    }

    /*跳转到用户修改界面*/
    @RequestMapping("/tousermodify")
    public ModelAndView toUserModify(int id) {
        ModelAndView mav = new ModelAndView();
        User user = new User();
        user.setId(id);
        user = userService.queryUserById(user);
        //将数据传入前端
        mav.addObject("birthday", new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));
        mav.addObject("users", user);
        mav.setViewName("usermodify");
        return mav;
    }

    /*用户修改*/
    @RequestMapping(value = "/usermodify", produces = "application/json; charset=utf-8")
    public ModelAndView userModify(User user, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        if (method.equals("modifyexe") && method != null) {
            //获取前端数据
            String id = request.getParameter("uid");
            String genders = request.getParameter("genders");
            String birthdays = request.getParameter("birthdays");
            //设置无法自动转换类型的数据，使其与user对象的属性匹配
            user.setId(Integer.valueOf(id));
            user.setGender(Integer.valueOf(genders));
            try {
                user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthdays));
            }catch (ParseException e){
                e.printStackTrace();
            }
            //设置修改者和修改时间
            user.setModifyBy(((User)request.getSession().getAttribute("user")).getId());
            user.setModifyDate(new Date());
            //执行修改操作
            int flag = userService.modifyUserById(user);
            //判断修改是否成功
            if(flag>0){
                mav.setViewName("redirect:/user/userlist?method=query");
            }else{
                mav.setViewName("redirect:/user/tousermodify");
            }
        }
        //ajax动态获取角色选择栏参数
        else if (method.equals("getrolelist") && method != null) {
            List<Role> roleList = roleService.getRoleList();
            try {
                //将roleList转换成json对象
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONArray.toJSONString(roleList));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }


}
